package logic

import (
	"context"
	"strconv"
	"time"
	"user-srv/common"
	"user-srv/user"

	"api/internal/svc"
	"api/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

type RealAuthLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewRealAuthLogic(ctx context.Context, svcCtx *svc.ServiceContext) *RealAuthLogic {
	return &RealAuthLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *RealAuthLogic) RealAuth(req *types.RealAuthRequest) (resp *types.Response, err error) {
	// todo: add your logic here and delete this line
	value := l.ctx.Value("userId").(string)
	userId, _ := strconv.Atoi(value)
	info, err := l.svcCtx.UserSrv.GetUserIdInfo(l.ctx, &user.GetUserIdInfoRequest{UserId: int64(userId)})
	if err != nil {
		return &types.Response{
			Code:    -1,
			Message: err.Error(),
			Data:    nil,
		}, nil
	}
	if info.ID != 0 {
		return &types.Response{
			Code:    -2,
			Message: "您已实名,请勿重复",
			Data:    nil,
		}, nil
	}
	cardInfo, err := l.svcCtx.UserSrv.GetIdCardInfo(l.ctx, &user.GetIdCardInfoRequest{IdCard: req.IdCard})
	if err != nil {
		return &types.Response{
			Code:    -3,
			Message: err.Error(),
			Data:    nil,
		}, nil
	}
	if cardInfo.ID != 0 {
		return &types.Response{
			Code:    -4,
			Message: "用户实名信息已被使用",
			Data:    nil,
		}, nil
	}
	s := req.IdCard[6:14]
	format := time.Now().Format("20060102")
	atoi, _ := strconv.Atoi(s)
	atoiForm, _ := strconv.Atoi(format)
	if atoiForm-atoi < 180000 {
		return &types.Response{
			Code:    -5,
			Message: "未满18岁,请成年后再来",
			Data:    nil,
		}, nil
	}
	if !common.RealAuth(req.RealName, req.IdCard) {
		return &types.Response{
			Code:    -6,
			Message: "实名认证失败",
			Data:    nil,
		}, nil
	}
	_, err = l.svcCtx.UserSrv.SaveRealAuthInfo(l.ctx, &user.SaveRealAuthInfoRequest{
		UserId:   int64(userId),
		RealName: req.RealName,
		IdCard:   req.IdCard,
	})
	if err != nil {
		return &types.Response{
			Code:    -7,
			Message: "保存实名认证失败",
			Data:    nil,
		}, nil
	}
	return &types.Response{
		Code:    0,
		Message: "实名认证成功",
		Data:    nil,
	}, nil
}
